package com.fone.player.storage.download;

import java.util.List;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.fone.player.entity.Download;
import com.fone.player.storage.FileDownloadDataBaseAdapter;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;

public class CacheDownloadService extends Service {
	private static final String TAG = CacheDownloadService.class
			.getSimpleName();
	private static DownloadMessageProtocol mDownloadMSGProtocol = null;
	private static Context sContext = null;

	public IBinder onBind(Intent intent) {

		if (mDownloadMSGProtocol != null) {
			return mDownloadMSGProtocol.mServiceStub;
		} else {
			L.e(TAG, "onBind", "mDownloadMSGProtocol=null");
			return null;
		}

	}

	public void onCreate() {
		super.onCreate();

		sContext = this;

		// 申请电源锁
		CPUWakeLock.acquireCpuWakeLock(this);

		v(TAG, "onCreate", "start");

		mDownloadMSGProtocol = new DownloadMessageProtocol();

		v(TAG, "onCreate",
				"init DownloadOfflineCacheManager mDownloadMSGProtocol="
						+ mDownloadMSGProtocol);

		DownloadOfflineCacheManager.init(mDownloadMSGProtocol);

		// 清理之前的通知栏
		v(TAG, "onCreate", "clear scrap Notification");

		List<Download> downloadList = FileDownloadDataBaseAdapter.getInstance()
				.getDownloadList(Download.DOWNLOAD_STATE_ALL);
		if (downloadList != null) {
			NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			for (Download download : downloadList) {
				notificationManager
						.cancel(download.getDownloadNotificationId());
			}
		}

		v(TAG, "onCreate", "initQueue start");

		// 初始化下载
		DownloadOfflineCacheManager.getInstance().initQueue();

	}

	public void onDestroy() {
		super.onDestroy();

		v(TAG, "onDestroy", "start");

		// 释放电源锁
		CPUWakeLock.releaseCpuWakeLock();

		// 关闭正在下载的通知栏
		NotificationHandle.getInstance().closeNotification();

		v(TAG, "onDestroy", "exit(0)");
		System.exit(0);

	}

	/**
	 * 判断是否有网络
	 */
	public static boolean isNetwork() {
		// L.v(TAG, "isNetwork", "sContext=" + sContext);
		return FoneUtil.isNetOk(sContext);
	}

	public DownloadAppManager getDownloadAppManager() {
		return DownloadAppManager.getInstance();
	}

	public DownloadOfflineCacheManager getDownloadOfflineCacheManager() {
		return DownloadOfflineCacheManager.getInstance();
	}

	public static void v(String TAG, String type, String msg) {
		L.v(TAG, type, msg);
	}

	public static void e(String TAG, String type, String msg) {
		L.e(TAG, type, msg);
	}
}
